package com.sakura.seckill.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sakura.seckill.pojo.Order;
import com.sakura.seckill.pojo.SeckillMessage;
import com.sakura.seckill.pojo.SeckillOrder;
import com.sakura.seckill.pojo.User;
import com.sakura.seckill.service.IGoodsService;
import com.sakura.seckill.service.IOrderService;
import com.sakura.seckill.service.ISeckillOrderService;
import com.sakura.seckill.utils.JsonUtil;
import com.sakura.seckill.vo.GoodsVo;
import com.sakura.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

/**
 * @author Sakura
 * @Date 2022-08-21 10:36
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private RedisTemplate redisTemplate;

    //下单操作
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message, Model model) {
        log.info("接收的信息：{}", message);

        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        //获取商品信息
        GoodsVo goodsVo = goodsService.findGoodVoByGoodsId(goodsId);
        //判断库存
        if (goodsVo.getStockCount() < 0) {
            return;
        }

        //判断是否重复抢购
        QueryWrapper<SeckillOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId())
                .eq("goods_id", goodsId);
        SeckillOrder seckillOrder = seckillOrderService.getOne(queryWrapper);
        //已经秒杀过
        if (seckillOrder != null) {
            model.addAttribute("errmsg", RespBeanEnum.REPEATE_ERROR.getMessage());
            return;
        }

        //下单操作
        seckillOrderService.seckill(user, goodsVo);

        //秒杀成功，删除缓存
//        if (order!=null){
//            redisTemplate.delete("goodsList");
//        }
//
//        model.addAttribute("order",order);
//        model.addAttribute("goods",goodsVo);
    }
}
